package com.mairuide.base_dict.station.service;

import com.mairuide._frame.utils.Testtrans;
import com.mairuide.base_dict.station.dao.StationInfoManageDao;
import com.mairuide.base_dict.station.dto.StationDto;
import com.mairuide.base_dict.station.pojo.Station;
import com.mairuide.entity.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-06-04 11:31
 */
@Service
public class StationInfoManageService {
    @Autowired
    StationInfoManageDao stationInfoManageDao;
    @PersistenceContext
    private EntityManager entityManager;
    public Station findOnebyId(Integer id){
        Station planeInfoManage = stationInfoManageDao.findOne(id);
        return planeInfoManage;
    }
    public void save(Station sd){
        stationInfoManageDao.save(sd);
    }
    public void del(Integer id){
        stationInfoManageDao.delete(id);
    }
    public PageResult findByPage(StationDto dto){
        PageResult result = createSpecification(dto);
        return result;
    }

    /**
     * 动态条件构建
     * @param searchMap
     * @return
     */
    private PageResult createSpecification(StationDto dto) {
        String sql = "select * from TB_STATION_INFO_MANAGE where 1=1 ";
        if (StringUtils.isNotBlank(dto.getKeyword())){
            sql += " and ( station_name like  '%" + dto.getKeyword() +"%' or location like '%"+dto.getKeyword()+"%') " ;
        }
        Query query = entityManager.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(new Testtrans(Station.class));
        List<Station> maps = query.getResultList();
        // 设置分页
        query.setFirstResult((dto.getPage() - 1) * dto.getRows());
        query.setMaxResults(dto.getRows());
        // 获取查询结果集
        List<Station> list = query.getResultList();
        PageResult pageResult = new PageResult(Long.valueOf(maps.size()), list);
        return pageResult;
    }
}
